import bitbrowser_api as api
import log
import pyppeteer
import asyncio
import random

async def like(ws_link :str, num :int = 6):
    # 设置默认点赞数量为6
    if num is None:
        num = 6
    
    try:
        # 连接到浏览器
        browser = await pyppeteer.connect(browserWSEndpoint=ws_link)
        # 打开新页面
        page = await browser.newPage()
        await page.setViewport({'width': 1366, 'height': 1024})
        # 导航到指定 URL
        await page.goto("https://www.facebook.com/")
        log.Info(f"成功打开网页: https://www.facebook.com/")
    except Exception as e:
        log.Error(f"连接浏览器或打开网页失败: {str(e)}")
        return
    
    try:
        log.Info(f"网页成功打开")
        log.Info(f"开始点赞,计划点赞{num}个")
        
        # 记录成功点赞的数量
        success_count = 0
        
        # 循环点赞指定次数
        for i in range(num):
            try:
                # 使用XPath定位具有aria-label="赞"的div元素
                like_button = await page.waitForXPath('//div[@aria-label="赞"]', timeout=10000)
                await like_button.click()
                success_count += 1
                log.Info(f"第{success_count}个点赞成功")
                
                # 随机等待1-3秒，模拟人工操作
                wait_time = random.randint(1, 3)
                await asyncio.sleep(wait_time)
                
            except Exception as e:
                log.Error(f"第{i+1}个点赞失败: {str(e)}")
                break
        
        log.Info(f"点赞任务完成，总共成功点赞{success_count}个")
    
    except Exception as e:
        log.Error(f"点赞过程出现异常: {str(e)}")

if __name__ == "__main__":
    ws_link = api.get_pyppeteer_wslink_by_ids(api.get_alive_ids()[0])
    asyncio.get_event_loop().run_until_complete(like(ws_link))
